package com.example.result.dao.db

import android.content.Context
import androidx.room.*
import androidx.paging.DataSource
import com.example.result.dao.vo.DaoContent
import com.example.result.dao.vo.DaoSection


@Database(
    entities = [DaoSection::class, DaoContent::class],
    version = 1,
    exportSchema = false
)
abstract class DaoDb : RoomDatabase() {
    companion object {
        val DB_NAME = "daodejing.db"
        fun create(context: Context, useInMemory: Boolean=false): DaoDb {
            val databaseBuilder = if (useInMemory) {
                Room.inMemoryDatabaseBuilder(context, DaoDb::class.java)
            } else {
                Room.databaseBuilder(context, DaoDb::class.java,
                    DB_NAME
                )
            }
            return databaseBuilder
                .fallbackToDestructiveMigration()
                .build()
        }
    }

    abstract fun sectionDao(): DaodejingSectionDao
    abstract fun contentDao(): DaodejingContentDao
}

@Dao
interface DaodejingSectionDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertSection(section: List<DaoSection>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertSection(section: DaoSection)

    @Delete
    fun deleteSection(section: List<DaoSection>)

    @Delete
    fun deleteSection(section: DaoSection)

    @Query("SELECT * FROM daodejingSection WHERE id = :id")
    fun getSection(id: Int): DaoSection

    @Query("SELECT * FROM daodejingSection")
    fun getAllSection(): DataSource.Factory<Int, DaoSection>


}

@Dao
interface DaodejingContentDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(content: List<DaoContent>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(content: DaoContent)

    @Delete
    fun delete(section: DaoContent)

    @Query("SELECT * FROM daodejingContent WHERE sectionId = :sectionId")
    fun get(sectionId: Int): List<DaoContent>
    @Query("SELECT * FROM daodejingContent WHERE sectionId = :sectionId")
    fun getForPageList(sectionId: Int): DataSource.Factory<Int, DaoContent>
}